package cn.matezk.lianlian.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.dao.DeviceDao;
import cn.matezk.lianlian.dao.SimRenewDao;
import cn.matezk.lianlian.dto.DeviceDto;
import cn.matezk.lianlian.dto.SimRenewDto;
import cn.matezk.lianlian.model.Device;
import cn.matezk.lianlian.model.SimRenew;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class WsFlowTask {
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private SimRenewDao simRenewDao;

    @XxlJob("wsFlowSyncTask")
    public void flowSync() {
        // 参数fwxxfYZsXRXD,admin@108674,370205 appId,账号,密码
        String params[] = XxlJobHelper.getJobParam().split(",");
        if (params.length != 3) return;
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setCardSource("");
        deviceDto.setPageNo(1);
        deviceDto.setPageSize(100);
        Map<String, Object> form = new HashMap<>();
        form.put("amount", params[1]);
        form.put("key", MD5.create().digestHex(params[2]));
        List<Device> cards = new ArrayList<>();
        while (true) {
            List<Device> deviceList = deviceDao.select(deviceDto);
            if (ObjectUtil.isEmpty(deviceList)) break;
            List<String> iccids = new ArrayList<>();
            for (Device device : deviceList) {
                if (ObjectUtil.isEmpty(device.getIccid()) || iccids.contains(device.getIccid()))  continue;
                iccids.add(device.getIccid());
            }
            if (ObjectUtil.isNotEmpty(iccids)) {
                form.put("iccids", String.join("_", iccids));
                String body = HttpUtil.get("http://tools.wosoiot.com:8080/interfaces/v1/batch/cardInfo.action", form);
                JSONObject object = JSONUtil.parseObj(body);
                if (object.containsKey("data")) {
                    JSONArray array = object.getJSONArray("data");
                    if (array.size() == 0)  continue;
                    for (int i = 0; i < array.size(); i ++) {
                        JSONObject item = array.getJSONObject(i);
                        if (!"1".equals(item.getStr("status")))  continue;
                        Date expireDate = item.getDate("expire_time", DateUtil.parseDate("2000-01-01"));
                        cards.add(Device.buildCard("WS", item.getStr("iccid"), expireDate));
                    }
                }
            }
            if (deviceList.size() < deviceDto.getPageSize())    break;
            deviceDto.setPageNo(deviceDto.getPageNo() + 1);
        }
        if (ObjectUtil.isNotEmpty(cards)) {
            List<List<Device>> array = CollUtil.split(cards, 500);
            for (List<Device> cs : array) {
                deviceDao.batchUpdateCardInfo(cs);
            }
        }
    }

    @XxlJob("wsFlowRenewTask")
    public void flowRenew() {
        // 参数fwxxfYZsXRXD,admin@108674,370205 appId,账号,密码
        String params[] = XxlJobHelper.getJobParam().split(",");
        if (params.length != 3) return;
        SimRenewDto simRenewDto = new SimRenewDto();
        simRenewDto.setAppId(params[0]);
        simRenewDto.setPageNo(1);
        simRenewDto.setPageSize(100);
        simRenewDto.setAppId(params[0]);
        Map<String, Object> form = new HashMap<>();
        form.put("amount", params[1]);
        form.put("key", MD5.create().digestHex(params[2]));
        List<String> iccids = new ArrayList<>();
        while (true) {
            List<SimRenew> renewList = simRenewDao.filter(simRenewDto);
            if (ObjectUtil.isEmpty(renewList)) break;
            for (SimRenew renew : renewList) {
                if (iccids.contains(renew.getIccid()))  continue;
                iccids.add(renew.getIccid());
                try {
                    form.put("iccid", renew.getIccid());
                    form.put("month", renew.getMonths());
                    String body = HttpUtil.get("http://tools.wosoiot.com:8080/interfaces/v1/rechargerenew.action", form);
                    JSONObject object = JSONUtil.parseObj(body);
                    int status = object.getInt("status");
                    if (status == 1) {
                        JSONObject data = object.getJSONObject("data");
                        String payno = data.getStr("payno");
                        renew.setPayno(payno);
                        simRenewDao.insertSelective(renew);
                    } else {
                        if ("1026".equals(object.getStr("code"))) {
                            // 账户余额不足直接退出
                            return;
                        }
                        log.error("续费失败: {}", object);
                    }
                } catch (Exception e) {
                    log.error("{}续费失败:{}", renew.getIccid(), e);
                }
            }
            if (renewList.size() < simRenewDto.getPageSize())    break;
            simRenewDto.setPageNo(simRenewDto.getPageNo() + 1);
        }
    }
}
